package com.chuan.icons;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Twitter extends SiteBase {
	private final String APP_URL = "http://melo9.appspot.com/api/statuses/followers.json";
	private String mPassword = "";
	public static String mAuthUser = "";
	public static String mAuthPassword = "";

	Twitter(FriendActivity context) {
		super(context);
		mSite = "twitter";
	}

	public JSONArray getAccountInfo() {
		JSONArray ary = new JSONArray();
		ary.put("username");
		ary.put("password");
		return ary;
	}

	@Override
	public Boolean getFriendsList(JSONObject info) {
		try {
			mUser = info.getString(Constants.PARAMETER_USER);
			mPassword = info.getJSONObject(Constants.PARAMETER_PARAMETER)
					.getString("password");
			mAuthUser = mUser;
			mAuthPassword = mPassword;
		} catch (JSONException e) {
			return false;
		}

		updateDiagInfo(R.string.str_login);
		String data = basicAuthDownload(APP_URL, mUser, mPassword);

		if (data == null) {
			updateDiagInfo(R.string.str_login_fail);
			return false;
		}

		updateDiagInfo(R.string.str_fetch_account);

		try {
			parseFriendsData(new JSONArray(data));
		} catch (JSONException e) {
			updateDiagInfo(R.string.str_fetch_account_fail);
			return false;
		}
		return true;
	}

	private void parseFriendsData(JSONArray ary) {
		JSONObject friend = null;
		String name, f_id, icon;
		for (int i = 0; i < ary.length(); ++i) {
			try {
				friend = ary.getJSONObject(i);
				name = friend.getString("name");
				f_id = friend.getString("id");
				icon = friend.getString("profile_image_url");

				addFriends(f_id, name, icon);
			} catch (JSONException e) {
				continue;
			}
		}
	}

	@Override
	public Boolean pairFriends(JSONObject info) {
		return pairFriendsByName(info);
	}
}
